package com.woniuxy.service.impl;

import com.woniuxy.dao.LoginDao;
import com.woniuxy.entity.RbacManager;
import com.woniuxy.entity.ResponseEntity;
import com.woniuxy.service.LoginService;
import com.woniuxy.utils.JWTUtils;
import com.woniuxy.utils.SecurityCryUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.security.auth.login.LoginException;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    LoginDao loginDao;
    @Autowired
    RedisTemplate redisTemplate;
    @Override
    public ResponseEntity login(String username, String password) throws LoginException {
        //通过加密算法，来生成新的密码
        String newPassword = SecurityCryUtils.generateEncryptedPassword(password, username);
        RbacManager rbacManager = loginDao.findOne(username,newPassword);
        if (Objects.nonNull(rbacManager)) {
            ResponseEntity responseEntity = new ResponseEntity(rbacManager);
            String token = JWTUtils.sign(rbacManager.getAccount(),rbacManager.getPassword());
//             把token当做key，把用户信息当做value!未来，就可以直接使用token查询出value！
            //使用String，来存对象！这个企业常用手段。30min过期，也就是ttl！
            redisTemplate.opsForValue().set(token,rbacManager,30, TimeUnit.MINUTES);
            responseEntity.put("token",token);
            return  responseEntity;
        }else {
            //直接返回401即可
            throw new LoginException("账号或密码错误！");
        }
    }
}